<?php

namespace app\shop\library;

use GatewayWorker\Lib\Gateway;

class ShopWorkerHelper
{
    private static ShopWorkerHelper $instance;

    public function __construct()
    {
        $config                   = config('worker_ws');
        Gateway::$registerAddress = "{$config['register']['ip']}:{$config['register']['port']}";
    }

    public static function instance(): ShopWorkerHelper
    {
        if (!isset(self::$instance)) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function bindUid(string $clientId, int|string $uid): static
    {
        Gateway::bindUid($clientId, $uid);

        return $this;
    }

    public function send(mixed $uid, string $type, mixed $data): void
    {
        $uid = is_array($uid) ? $uid : [$uid];

        // 过滤掉不在线的用户
        $onlineUid = array_filter($uid, function ($id) {
            return Gateway::isUidOnline($id);
        });

        Gateway::sendToUid($onlineUid, $this->buildMessage($type, $data));
    }

    private function buildMessage(string $type, mixed $data): ?string
    {
        return json_encode([
            'type' => $type,
            'data' => $data,
            'time' => time(),
        ]);
    }
}
